package uestc.lj.gulishop.seckill.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import uestc.lj.common.constant.AuthServerConstant;
import uestc.lj.common.vo.MemberResponseVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author:Crazlee
 * @Date:2021/6/15
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVO> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // 秒杀请求需要判断是否登录
        boolean match = antPathMatcher.match("/kill", requestURI);
        if (match) {
            MemberResponseVO memberResponseVO = (MemberResponseVO) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
            if (memberResponseVO != null) {
                loginUser.set(memberResponseVO);
                return true;
            } else {
                // 没登陆
                request.getSession().setAttribute("msg", "您还未登录，请先登录！");
                response.sendRedirect("http://auth.gulishop.com/login.html");
                return false;
            }
        }
        return true;
    }
}
